<?php
class ForeignAction extends CommonAction {

    public function index()
    {
        $foreign = M('Foreign');
        parent::page($foreign->count());
        $data = $foreign->limit($this->limit)
                        ->select();

        $this->assign('data', $data);
        $this->display();
    }

    public function add()
    {
        $foreign = M('Foreign');
        if(isset($_POST['send']))
        {
            $this->validate(self::$ADD_SEC);
            $data['name'] = $this->_post('name');
            if($foreign->add($data))
                redirectByModal('添加单位成功!', self::$SUCCESS, __URL__ . '/index');
        }
        $this->display();
    }

    public function update($id)
    {
        $foreign = M('Foreign');
        $currentData = $foreign->field(array('id', 'name'))->where('id='.$id)->find();

        if(isset($_POST['send']))
        {
            $this->validate(self::$UPDATE_SEC);
            $data['name'] = $this->_post('name');
            $data['id'] = $this->_post('id');
            $foreign->save($data);
            redirectByModal('修改单位成功!', self::$SUCCESS, __URL__.'/index');
        }
        $this->assign('data', $currentData);
        $this->display();
    }

    public function delete()
    {
        $id = $this->_post('id');
        $foreign = M('Foreign');
        if($foreign->where('id='.$id)->delete())
            redirectByModal('删除单位成功!', self::$SUCCESS, __URL__ . '/index');
    }

    // 验证
    private function validate($sec)
    {
        $name = $this->_post('name');
        if($name == '')
            redirectByModal('单位名称必须填写!', self::$ERROR);
        else if(mb_strlen($name, 'utf-8') > 30)
            redirectByModal('单位名称不能超过30位!', self::$ERROR);
        else if($sec == 'add')
        {
            $foreign = M('Foreign');
            if($foreign->where("name='$name'")->find())
                redirectByModal('单位名称已经存在!', self::$ERROR);
        }
    }
}